//
//  SetViewController.swift
//  YLH
//
//  Created by qinjiangtao on 2024/1/12.
//

import UIKit

class SetViewController: QIBaseViewController {
    
    private var titleArr = [String]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "设置"
        
        titleArr = ["清理缓存", "注销账号"]
        view.addSubview(tableView)
        view.addSubview(quitBtn)
    }
    
    @objc private func quitBtnClick() {
        Defaults[\.isLogin] = false
        Defaults[\.bearer] = ""
        
        let window = UIApplication.shared.keyWindow
        window?.switchRootCtrl()
    }
    
    private lazy var quitBtn: UIButton = {
        let quitBtn = UIButton().then {
            $0.frame = CGRect(x: 16, y: SCREEN_HEIGHT - 100, width: SCREEN_WIDTH - 32, height: 44)
            $0.backgroundColor = MainColor
            $0.titleLabel?.font = SYSFONT(ofSize: 14)
            $0.setTitle("退出登录", for: .normal)
            $0.setTitleColor(.white, for: .normal)
            $0.addRoundedCorners(withRadius: 22)
            $0.addTarget(self, action: #selector(quitBtnClick), for: .touchUpInside)
        }
        return quitBtn
    }()

    private lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT)
        tableView.backgroundColor = .white
        tableView.delegate = self
        tableView.dataSource = self
        if #available(iOS 15.0, *) {
            tableView.sectionHeaderTopPadding = 0
        } else {}
        return tableView
    }()

}

extension SetViewController: UITableViewDataSource, UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        titleArr.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        50
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        cell.selectionStyle = .none
        cell.accessoryType = .disclosureIndicator
        cell.textLabel?.text = titleArr[indexPath.row]
        cell.textLabel?.textColor = Color333333
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.row == 0 {
            DispatchQueue.global().async {
                ImageCache.default.clearDiskCache {
                    DispatchQueue.main.async {
                        ShowHUD(str: "清除成功")
                    }
                }
            }
            
        } else {
            QINetworkManager.requestJson(urlStr: "/User/userOff", parameters: [:]) { json in
                print(json)
                ShowHUD(str: "账户已注销")
                self.quitBtnClick()
            }
        }
    }
}
